//
//  ZBMyChujiaVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2024/9/3.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
 
class ZBMyChujiaVC: ZyaTenderBaseTableVC,UISearchBarDelegate {
    
    var page = 1
    
   
   
    var dataArray = [ZyaZtbContentModel]()
    var z_zb_id = "" // 出价记录使用
    
    
    var btnflag = "1"
    
    
    var followTag = ""
    var helper = ZyaTenderHelper()
    private var searchBar:UISearchBar?
    
    
    init(z_zb_id:String = "",searchTitle:String = "",followTag:String = "0") {
        super.init(nibName: nil, bundle: nil)
     
        self.followTag = followTag
        self.z_zb_id = z_zb_id
        self.helper.filterPa!.searchTitle = searchTitle
    }
 
    lazy var slideV_tb:SlideView = {
        let v = SlideView(frame: CGRect(x:0,y:0,width: KSGlobal.screenW,height: KSGlobal.screenH), arr: [SlideContent(type: .singleSelect, title: "时间",dataArr: ["全部", "3日内", "7日内", "1月内", "3月内"].map{ SeString(title: $0, ks_selected: ($0 == "全部")) },numberOfRow: 3,open: true),SlideContent(type: .singleSelect, title: "类型",dataArr: zyaleixingArr.map{ SeString(title: $0, ks_selected: ($0 == "全部")) },numberOfRow: 3,open: true),SlideContent(type: .actionClo,title: "区域", inputStr: "全部",actionClo: { cuIndex in
            
            let vc = ProvinceCityController(selectType: .city)
            vc.citySelectClosure = { province,city in
            
                self.slideV_tb.arr[2].inputStr = city
                self.slideV_tb.tableView.reloadData()
            }
            if let window = getKeyWindow() {
                let nav = BaseNavigationController()
                nav.viewControllers = [vc]
                window.rootViewController?.present_FullScreen(to: nav)
            }
//            let window = UIApplication.shared.keyWindow!.rootViewController!
            
        
            
        })])
        return v
    }()
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setSearchBar()
        self.title = "我的报价"
        helper.callTableRefreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
            
        }
    
        
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableView.automaticDimension
        
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter { [unowned self] in
            self.page += 1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
         tableView.register(XSBaojiaCell.self, forCellReuseIdentifier: XSBaojiaCell.identifier)
 
        
        tableView.tableFooterView = UIView()
        
        
    }
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
    func setSearchBar () {
        searchBar = TenderSearchBar(frame:CGRect(x:5,y:5,width:KSGlobal.screenW - 60,height:40))
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        searchBar?.backgroundImage = UIImage()
       

        searchBar!.searchTextField.backgroundColor = .white
          searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
        searchBar!.searchTextField.layer.borderColor = Theme.primaryColor().cgColor
       searchBar!.searchTextField.layer.borderWidth = 1
        
        
        searchBar!.text = self.helper.filterPa!.searchTitle
        searchBar!.placeholder = "搜索报价信息"
        searchBar!.delegate = self
        let searchView = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW ,height:50))
        searchView.addSubview(searchBar!)
        
       
        self.slideV_tb.confirmClosure = { arr in
          
            let ss = arr[0].dataArr!.filter{ $0.ks_selected }
            if ss.count > 0 {
                 if ss.first!.title == "全部" {
                    self.helper.filterPa!.startDate = ""
                    self.helper.filterPa!.endDate = ""
                        
                    } else if ss.first!.title == "3日内" {
                        self.helper.filterPa!.startDate = Date.todayPres(3)
                        self.helper.filterPa!.endDate = Date.today
                        
                    } else if ss.first!.title == "7日内" {
                        self.helper.filterPa!.startDate = Date.todayPres(7)
                        self.helper.filterPa!.endDate = Date.today
                        
                    } else if ss.first!.title == "1月内" {
                        self.helper.filterPa!.startDate = Date.preMonthsWithNowday(1)
                        self.helper.filterPa!.endDate = Date.today
                        
                    } else if ss.first!.title == "3月内" {
                        self.helper.filterPa!.startDate = Date.preMonthsWithNowday(3)
                        self.helper.filterPa!.endDate = Date.today
                    }
              } else {
                self.helper.filterPa!.startDate = ""
                self.helper.filterPa!.endDate = ""
            }
            let ss1 = arr[1].dataArr!.filter{ $0.ks_selected }
            if ss1.count > 0 {
                self.helper.filterPa!.categoryNm = ss1.first!.title
              } else {
                self.helper.filterPa!.categoryNm = ""
                
            }
            
            
            
           let city = arr[2].inputStr

            if city == "全部" {
                self.helper.filterPa!.zCity = ""
            } else {
                self.helper.filterPa!.zCity = city
            }
           
            
            self.slideV_tb.close()
            self.tableView.mj_header?.beginRefreshing()
        }
        
        let moreBtn = UIButton(frame:CGRect(x:KSGlobal.screenW - 50,y:5,width:40 ,height:40))
        moreBtn.setBackgroundImage(UIImage(named: "filter_more"), for: .normal)
        moreBtn.addTouchUpInSideAction { _ in
            
            
            let window = UIApplication.shared.keyWindow!.rootViewController!.view!
            
                window.addSubview(self.slideV_tb)
        
      
        }
        searchView.addSubview(moreBtn)
        self.tableView.tableHeaderView = searchView
    
    }
   
    @objc func mapAction() {
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.helper.filterPa!.searchTitle = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let one = self.dataArray[indexPath.row]
        
            guard let cell = tableView.dequeueReusableCell(withIdentifier: XSBaojiaCell.identifier, for: indexPath) as? XSBaojiaCell else {
                fatalError("cell error")
            }
         
            cell.makeConstrainsts()
         
            
            
        one.listType = .TB
            one.innerType = .tbMytbKHW
            cell.btnDtradeType.isHidden = false
            
            cell.one = one
         
            return cell
         
        
        
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
     
            var idkey:String = ""
          
                idkey = self.dataArray[indexPath.row].zZbId.unwrap
         
            zyago2TenderInfoVC(listType: .TB, fromVC:self,idkey:idkey,innerType:.tbMytbKHW)
            
        
        
        
    }
    func network () {
        let api = self.helper.titleStrToAPI(listType:.TB,titleStr: .tbMytbKHW, startDate: self.helper.filterPa!.startDate, endDate: self.helper.filterPa!.endDate, maxValue: self.helper.filterPa!.maxMoney, minValue: self.helper.filterPa!.minMoney,zprovince: self.helper.filterPa!.zProvince, zcity: self.helper.filterPa!.zCity, searchTitle: self.helper.filterPa!.searchTitle, page: self.page, z_zb_id: z_zb_id,z_status: self.helper.filterPa!.zStatus,outDate:self.helper.filterPa!.outDate,category: self.helper.filterPa!.categoryNm,followTag: self.followTag)
        
        
        KSNetwork.shared.doRequest(api,showHud: false) { [weak self] (data:BaseResult<ZyaZtbContentModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < 10 {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    
    deinit {
        print("tenderfirst 销毁")
    }
}
